/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.slice;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.ResourceHelper;
import com.lingeringdream.luciole.helper.list.ClassResultProvider;
import com.lingeringdream.luciole.model.Constants;
import com.lingeringdream.luciole.model.helper.ResultSetHelper;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.utils.net.Uri;

import java.util.Locale;

/**
 * 结果列表页面
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/5/2
 */
public class ResultListSlice extends AbilitySlice {
    private final HiLogLabel TAG =  new HiLogLabel(HiLog.LOG_APP, 0x13, ResultListSlice.class.getSimpleName());
    /**
     * 输入关键字
     */
    private String input;
    /**
     * 判断页面是类别还是咨询
     */
    private boolean isClassify;
    private boolean isChinese;

    private ListContainer listContainer;
    private DirectionalLayout statusBar;
    private TextField field;


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_result);

        isClassify = intent.getBooleanParam("isClassify", true);
        input = intent.getStringParam("input");
        if (isClassify && input != null) {
            initClassifyList();
        } else {
            initSearchBar();
        }
        listContainer = findComponentById(ResourceTable.Id_result_list);
        Image back = findComponentById(ResourceTable.Id_result_back);
        back.setClickedListener(component -> terminate());

        setStatusBar();
    }

    @Override
    protected void onActive() {
        super.onActive();
        isChinese = "zh".equals(Locale.getDefault().getLanguage());
        HiLog.info(TAG, Locale.getDefault().getLanguage());
    }

    @Override
    protected void onStop() {
        super.onBackground();
        statusBar.removeAllComponents();
        field.setText("");
    }

    /**
     * 设置沉浸式状态栏
     */
    private void setStatusBar() {
        getWindow().setStatusBarVisibility(WindowManager.LayoutConfig.MOD_APPLICATION_OVERLAY);
        getWindow().setStatusBarColor(ResourceHelper.getColorInt(getContext(),
                ResourceTable.Color_main_default, 0xFFFFFFFF));
        DisplayManager displayManager = DisplayManager.getInstance();
        Point realPoint = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getRealSize(realPoint);
        Point point = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getSize(point);
        int height = realPoint.getPointYToInt() - point.getPointYToInt();

        Component statusBarComponent = new Component(getContext());
        statusBarComponent.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, height
        ));

       statusBar = findComponentById(ResourceTable.Id_result_statusBar);

        statusBar.addComponent(statusBarComponent);

    }

    /**
     * 初始化搜索栏
     */
    public void initSearchBar() {
        field = findComponentById(ResourceTable.Id_result_textField);
        field.addTextObserver((s, i, i1, i2) -> {
            input = s;
        });
        field.setInputMethodOption(InputAttribute.ENTER_KEY_TYPE_SEND);
        field.setKeyEventListener((component, keyEvent) -> {
            if (keyEvent.getKeyCode() == KeyEvent.KEY_ENTER) {
                if (isClassify) {
                    initClassifyList();
                } else {
                    initNewsList();
                }
            }
            return false;
        });
        field.requestFocus();
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.delayDispatch(field::simulateClick, 300);
    }

    /**
     * 分类数据处理
     */
    private void initClassifyList() {
        ClassResultProvider provider = new ClassResultProvider(this,null,isChinese);
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        if (isChinese) {
            predicates.equalTo("cname", input);
        }else {
             predicates.equalTo("ename", input);
        }
        predicates.like("name", input);
        DataAbilityHelper helper = DataAbilityHelper.create(this);
        try {
            ResultSet resultSet = helper.query(Uri.parse(Constants.TABLE_CLASS.getValue()), null, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                HiLog.info(TAG, "query: resultSet is null or no result found");
                return;
            }
            resultSet.goToFirstRow();
            while (resultSet.goToNextRow()) {
                provider.addItem(ResultSetHelper.resultSet2Classification(resultSet));
            }

        } catch (Exception e) {
            HiLog.error(TAG, "query: " + e.getMessage());
        }finally {
            helper.release();
        }

        listContainer.setItemProvider(provider);
    }


    /**
     * 资讯数据处理
     */
    private void initNewsList() {

    }
}